<template>
	<view class="container flex-c">
		<uni-nav-bar class="ch-nav" height="88rpx" backgroundColor="#ffffff" leftWidth="90rpx" rightWidth="90rpx" color="#333" :fixed="true" :padding="false" :border="true" @clickLeft="$goBack(1)">
			<template slot="left">
				<image class="left" src="@/public/images/public/dhl_fhjt.png" mode="aspectFit"></image>
			</template>
			<text class="title">提交专家信息</text>
			<template slot="right"></template>
		</uni-nav-bar>
		<view class="body flex-c">
			<view class="card avatar flex-c">
				<view class="title flex-r ac jsb navborder">
					<text class="text-primary">头像</text>
					<view class="select-box flex-c ac jc" @tap="chooseImg('avatar')">
						<image :src="expert.avatar || $CHS.defaultExpertAvatar" mode="aspectFill"></image>
						<text class="text-mini color-white">{{expert.avatar ? '点击更换' : '点击上传'}}</text>
					</view>
				</view>
				<text class="info text-small color-grey">提示：优先使用本人照片作为头像（正装正面照优先、方便后续banner包装）。其次使用账号名称组成的艺术字头像，不建议使用球星照片作为头像。</text>
			</view>
			<view class="card name flex-c">
				<view class="title flex-r ac jsb navborder">
					<text class="text-primary">姓名</text>
					<input class="name-input" type="text" v-model="expert.name" :maxlength="5" @input="inputName" confirm-type="next" placeholder="请输入五个字以内的姓名"></input>
				</view>
				<text class="info text-small color-grey">提示：优先使用本人真实姓名。如使用昵称，不得与其他竞品平台、个人社交媒体昵称雷同。</text>
			</view>
			<view class="card remark flex-c">
				<view class="title">
					<text class="text-primary">简介</text>
				</view>
				<view class="text-box">
					<textarea class="remark-input" v-model="expert.intro" :maxlength="100" @input="inputRemak"></textarea>
					<view class="placeholder">
						<text v-show="!expert.intro">
							1. 最少20字，最多100字。
							2. 简介内容优先体现自己的足球类相关经验或擅长的赛事领域。
							3. 如具有类似足球类经验或在其他竞品平台、个人社交媒体有账号，请提供相关截图信息。
						</text>
					</view>
				</view>
			</view>
			<view class="card upload flex-c">
				<view class="title flex-r">
					<text class="text-primary">上传照片</text>
					<text class="text-small color-grey">（最多可上传9张照片）</text>
				</view>
				<view class="upload-image flex-r">
					<view class="image-list choose-image" @tap="chooseImg('image')" v-if="imageList.length < 9">
						<image src="@/public/images/apply/djsctp.png" mode="aspectFit"></image>
						<text class="color-grey">点击上传图片</text>
					</view>
					<view class="image-list" v-for="(item, index) in imageList" :key="index">
						<image :src="item" mode="aspectFill" @tap="previewImage(imageList, item)"></image>
						<image class="icon" src="@/public/images/user/sctp.png" mode="aspectFit" @tap="deleteImg(index)"></image>
					</view>
				</view>
			</view>
		</view>
		<view class="foot bottom-ios">
			<view class="submit-box" @tap="goNext()">
				<button :class="{'active': next}">下一步</button>
			</view>
		</view>
		<view class="cropper-wrap" v-if="cropperImg">
			<view class="cropper-wrap-tools">
				<view class="cropper-wraper-cancel" @click="cancelCropper">取消</view>
				<view class="cropper-wraper-confirm" @click="confirmCorpper">确定</view>
			</view>
			<image-cropper
				cutWidth="200px"
				id="image-cropper"
				:zoom="1"
				:angle="0"
				:keepRatio="true"
				:showCtrlBorder='true'
				:disableRotate='true'
				:imageCenter="true"
				:disableCtrl="true"
				fileType="jpg"
				:src="cropperImg"
				@load="cropperLoaded"
				@cropped="cropped"
			  />
		</view>
	</view>
</template>

<script>
	import * as qiniu from 'qiniu-js'
	export default {
		data() {
			return {
				expert: {
					avatar: null,
					name: null,
					intro: '',
					imgUrl: ''
				},
				imageList: [],
				cropperImg: null,
				croppedImg: null,
				
				textNum: 0
			};
		},
		components: {
			ImageCropper: () => import('../components/nice-cropper/cropper.vue')
		},
		computed: {
			next() {
				return this.expert.name && this.expert.avatar && this.expert.intro.length >= 20
			},
			user() {
				return this.$store.state.user
			}
		},
		onLoad() {
			let expert = uni.getStorageSync('apply_expert')
			if(expert){
				if(expert.userId == this.user.userId){
					this.expert = expert.data
					if(this.expert.imgUrl){
						this.imageList = this.expert.imgUrl.split(',')
					}
				}else{
					uni.removeStorageSync('apply_expert')
				}
			}
			console.log(this.imageList);
		},
		methods: {
			//下一步
			goNext() {
				if(this.next){
					this.$http.get({
						url: '/api/applyUgc/checkName',
						data: {
							name: this.expert.name
						}
					}).then(res => {
						console.log(res);
						if(res.code == 200 && res.success){
							this.$CHS.getQiniuToken().then(async (result)=>{
								this.token = result.token
								this.imageDomain = result.url
								//开始上传图片
								this.$ShowLoading({show: true})
								let res = await this.uploadAvatar()
								if(res){
									this.uploadAllImg().then((res)=>{
										console.log(res);
										this.$ShowLoading({show: false})
										this.expert.imgUrl = this.imageList.toString()
										//本地存储专家信息
										let expertInfo = {
											userId: this.user.userId,
											data: this.expert
										}
										uni.setStorageSync('apply_expert', expertInfo)
										this.$ShowToast({text: '专家信息提交成功'})
										this.$Router.replace({name: 'applyarticle'})
									}).catch((e)=>{
										console.log(e);
										this.$ShowLoading({show: false})
									})
								}else{
									this.$ShowLoading({show: false})
								}
							}).catch((err) => {
								console.log(err);
								uni.showToast({
									title: '网络异常，请重试',
									icon: 'none'
								})
							})
						}else{
							uni.showToast({
								title: res.message || '提交失败，请稍后重试',
								icon: 'none'
							})
						}
					}).catch((err) => {
						console.log(err);
						uni.showToast({
							title: '网络异常，请重试',
							icon: 'none'
						})
					})
				}else{
					if(!this.expert.avatar){
						uni.showToast({
							title: '请选择头像',
							icon: 'none'
						})
					}else if(!this.expert.name){
						uni.showToast({
								title: '请输入姓名',
							icon: 'none'
						})
					}else if(this.expert.intro.length < 20){
						uni.showToast({
							title: '简介最少20个字',
							icon: 'none'
						})
					}
				}
			},
			//计算输入字数
			inputName(e) {
				console.log(e);
				let nickname = e.detail.value.trim()
				this.textNum = nickname.length
				if(this.textNum == 5){
					uni.showToast({
						title: '最多输入5个字符',
						icon: 'none'
					})
				}
				this.$nextTick(()=>{
					this.expert.name = nickname
				})
			},
			inputRemak(e){
				console.log(e);
				let remark = e.detail.value.trim()
				if(remark.length == 100){
					uni.showToast({
						title: '最多输入100个字符',
						icon: 'none'
					})
				}
				this.$nextTick(()=>{
					this.expert.intro = remark
				})
			},
			//选择图片
			chooseImg(type) {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					extension: ['jpg','png'],
					success: (res) => {
						console.log(res);
						if(type == 'avatar'){
							this.cropperImg = res.tempFilePaths[0];
						}else{
							//this.uploadImage(res.tempFiles[0])
							this.imageList.unshift(res.tempFilePaths[0])
						}
					}
				});
			},
			//删除图片
			deleteImg(index){
				this.imageList.splice(index, 1)
			},
			//图片加载完成触发
			cropperLoaded(image){
				this.croppedImg = image.path
			},
			//每次操作裁剪触发
			cropped(imagePath, imageInfo) {
				console.log(imageInfo);
				this.croppedImg = imagePath
			},
			//取消裁剪
			cancelCropper(){
				this.cropperImg = ''
				this.croppedImg = ''
			},
			//确认完成裁剪
			confirmCorpper(){
				this.cropperImg = ''
				this.expert.avatar = this.croppedImg
			},
			//上传头像图片
			async uploadAvatar(){
				if(this.expert.avatar.indexOf(this.imageDomain) > -1){
					return true
				}else{
					let file = this.base64ConvertFile(this.expert.avatar)
					//七牛上传请求
					let res = await this.qiniuUploadImage(file)
					if(res.key){
						this.expert.avatar = this.imageDomain + '/' + res.key
						this.croppedImg = ''
						return true
					}else{
						uni.showToast({
							title: '图片上传失败，请检查网络并重试',
							icon: 'none'
						})
						return false
					}
				}
			},
			//上传全部图片
			uploadAllImg(){
				return new Promise((resolve,reject)=>{
					let rpNum = 0
					let len = this.imageList.length
					if(len == 0){
						resolve(this.imageList);
					}else{
						this.imageList.forEach( async (url, index) => {
							if(url.indexOf(this.imageDomain) > -1){
								rpNum += 1
								if(rpNum == len){
									resolve(this.imageList);
								}
							}else{
								try {
									let name = Date.now() + '.png'
									let type = 'image/png'
									await this.convertImgToBlob(url, (blob)=>{
										let file = new window.File([blob], name, { type: type })
										this.qiniuUploadImage(file).then((res)=>{
											let newSrc = this.imageDomain + '/' + res.key
											this.imageList[index] = newSrc
											rpNum += 1
											if(rpNum == len){
												resolve(this.imageList);
											}
										}).catch((res)=>{
											console.log(res);
											reject(false);
											uni.showToast({
												title: '图片上传失败，请检查网络并重试',
												icon: 'none'
											})
										})
									}, (url)=>{
										console.log(url);
										reject(false);
										uni.showToast({
											title: '图片上传失败，请检查网络并重试',
											icon: 'none'
										})
									})
								} catch(e) {
									console.log(e);
									reject(false);
									uni.showToast({
										title: '图片上传失败，请检查网络并重试',
										icon: 'none'
									})
								}
							}
						})
					}
				})
			},
			//七牛上传图片
			qiniuUploadImage(file) {
				return new Promise((resolve,reject)=>{
					let type = file.type.substr(6)
					let randomStr = this.$CHS.randomString(10)
					let key = Date.now() + randomStr + 'H5.' + type
					const observer = {
						next(res){
							console.log(res);
						},
						error(err){
							console.log(err);
							reject(err)
						},
						complete(res){
							console.log(res);
							resolve(res)
						}
					}
					const options = {
						quality: 0.4,
						noCompressIfLarger: true
					}
					//压缩图片
					qiniu.compressImage(file, options).then(data => {
						const observable = qiniu.upload(data.dist, key, this.token)
						const subscription = observable.subscribe(observer) // 上传开始
					})
				})
			},
			// 64转file
			base64ConvertFile(urlData) {
				var arr = urlData.split(',')
				var type = arr[0].match(/:(.*?);/)[1]
				var fileExt = type.split('/')[1]
				var bstr = atob(arr[1])
				var n = bstr.length
				var u8arr = new Uint8Array(n)
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n);
				}
				return new File([u8arr], Date.now() + 'H5.' + fileExt, {
					type: type
				});
			},
			convertImgToBlob(url, callback, error) {
				const img = new Image()
				img.crossOrigin = 'Anonymous' 
				img.onload = function () {
					let canvas = document.createElement('canvas')
					const ctx = canvas.getContext('2d')
					canvas.height = this.height
					canvas.width = this.width
					ctx.drawImage(this, 0, 0)
					canvas.toBlob(callback)
					canvas = null
				}
				img.onerror = function() {
					error(url)
				}
				img.src = url
			},
			//图片预览
			previewImage(tempFilePaths, current){
				console.log(tempFilePaths);
				uni.previewImage({
					current: current,
					urls: tempFilePaths,
					loop: true
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container{
		padding: 0;
	}
	.body{
		margin-bottom: calc(140rpx + var(--safe-area-inset-bottom) + var(--vh-offset, 0px));
		.card{
			background-color: #fff;
			margin-top: 20rpx;
			padding: 0rpx 20rpx 20rpx;
			.text-primary{
				font-weight: 500;
			}
			.info{
				margin-top: 20rpx;
				line-height: 36rpx;
				text-align: justify;
			}
		}
		.avatar{
			.title{
				height: 120rpx;
				.select-box{
					position: relative;
					image{
						width: 104rpx;
						height: 104rpx;
						border-radius: 50%;
					}
					.color-white{
						position: absolute;
						width: 104rpx;
						height: 104rpx;
						line-height: 104rpx;
						text-align: center;
						background: rgba(0, 0, 0, 0.4);
						border-radius: 50%;
					}
				}
			}
		}
		.name{
			.title{
				height: 96rpx;
				.name-input{
					flex: 2;
					text-align: right;
					font-size: 26rpx;
					/deep/ .input-placeholder{
						font-size: 26rpx;
						color: #B3B3B3;
					}
				}
			}
		}
		.remark{
			padding: 30rpx 20rpx;
			.text-box{
				width: 100%;
				position: relative;
				.remark-input{
					width: 100%;
					z-index: 2;
					margin-top: 20rpx;
					height: 320rpx;
					background: transparent;
					border-radius: 10rpx;
					padding: 20rpx;
					font-size: 26rpx;
					line-height: 42rpx;
					box-sizing: border-box;
					/deep/ .textarea-placeholder{
						font-size: 26rpx;
						font-family: Source Han Sans CN;
						font-weight: 400;
						color: #B3B3B3;
					}
				}
				.placeholder{
					z-index: 1;
					padding: 20rpx;
					background: #F2F5FA;
					border-radius: 10rpx;
					position: absolute;
					top: 20rpx;
					bottom: 0;
					left: 0;
					right: 0;
					font-size: 26rpx;
					font-family: Source Han Sans CN;
					font-weight: 400;
					color: #B3B3B3;
					line-height: 42rpx;
				}
			}
		}
		.upload{
			padding: 30rpx 20rpx;
			.upload-image{
				margin-top: 20rpx;
				flex-wrap: wrap;
				.image-list{
					margin-right: 22rpx;
					position: relative;
					width: 222rpx;
					height: 222rpx;
					image{
						width: 222rpx;
						height: 222rpx;
						border-radius: 10rpx;
					}
					.icon{
						position: absolute;
						top: 0;
						right: 0;
						width: 48rpx;
						height: 48rpx;
						border-radius: 0;
					}
				}
				.image-list:nth-child(3n){
					margin-right: 0;
				}
				.image-list:nth-child(n+4){
					margin-top: 20rpx;
				}
				.choose-image{
					margin-right: 22rpx;
					position: relative;
					width: 222rpx;
					height: 222rpx;
					border-radius: 10rpx;
					image{
						width: 222rpx;
						height: 222rpx;
					}
					text{
						position: absolute;
						top: 130rpx;
						left: 32rpx;
						color: #B3B3B3;
					}
				}
			}
		}
	}
	.foot{
		max-width: $max-width;
		margin: $pc-margin;
		background-color: #fff;
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		box-shadow: 0px -1px 0px 0px #EDEDED;
		z-index: 5;
		.submit-box{
			margin: 16rpx 20rpx;
			button{
				height: 88rpx;
				line-height: 88rpx;
				border-radius: 44rpx;
			}
		}
	}
	.cropper-wrap {
		max-width: $max-width;
		margin: $pc-margin;
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		height: calc(100vh - var(--vh-offset, 0px) - var(--safe-area-inset-bottom));
		z-index: 6;
		background-color: rgba(0, 0, 0, 1);
		.cropper-wrap-tools {
			position: absolute;
			left: 0;
			top: 156rpx;
			width: 100%;
			display: flex;
			justify-content: space-between;
			z-index: 66;
			.cropper-wraper-cancel , .cropper-wraper-confirm {
				width: 250rpx;
				height: 88rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				color: #FFFFFF;
				font-size: 32rpx;
			}
		}
	}
</style>
